<template>




<div class="merak-container-has-aside" curPageName="7dsfds534687">




   




      <div class="merak-aside"><treeNode  @node-change="nodeChange" :defTreeValue="org_id"></treeNode></div>
      <div class="merak-card merak-container-has-search" v-waterMarker>
        <div >
           
            <searchBar  :close-plan="true" :close-advanced="true"  ref="searchbar" :placeholder='$t("manage_record.placeholder")'  :search_val=search_val @search-event="searchBarPost"  v-model="searchform">

            <!-- 高级搜索弹出框 插槽-->
            <template #searchForm>
                    <!--  高级搜索弹出框内容-->
                    <div class="modal-content">
                    <div class="modal-title"> </div>

                    <div class="modal—body">
                        <el-scrollbar height="100%">
                        <div class="scrollbar-content">
                            <!-- 已选参数 组件-->
                            <selectedParams v-model="searchform" label="label" val="value" option-key="options"></selectedParams>

                            <!-- 表单 -->
                            <el-form :model="searchform" label-position="top" ref="ruleFormRef">
                            <merakColapse :is-active="false">
                                <template #header>基本信息</template>

                                <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item :label="searchform.org_company.label">
                                    <el-select style="width: 100%" v-model="searchform.org_company.value" :placeholder='$t("merak.placeholder_select")'  clearable>
                                        <el-option
                                        v-for="option in searchform.org_company.options"
                                        :key="option"
                                        :label="option.label"
                                        :value="option.value"
                                        />
                                    </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item :label="searchform.org_department.label">
                                    <el-select
                                        style="width: 100%"
                                        v-model="searchform.org_department.value"
                                        placeholder="请选择..."
                                        clearable
                                    >
                                        <el-option
                                        v-for="option in searchform.org_department.options"
                                        :label="option.label"
                                        :value="option.value"
                                        />
                                    </el-select>
                                    </el-form-item>
                                </el-col>
                                </el-row>

                                <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item :label="searchform.job_nature.label">
                                    <el-select style="width: 100%" v-model="searchform.job_nature.value" :placeholder='$t("merak.placeholder_select")' clearable>
                                        <el-option
                                        :label="option.label"
                                        :value="option.value"
                                        v-for="option in searchform.job_nature.options"
                                        :key="option"
                                        />
                                    </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item :label="searchform.status.label">
                                    <el-select style="width: 100%" v-model="searchform.status.value" :placeholder='$t("merak.placeholder_select")' clearable>
                                        <el-option
                                        :label="option.label"
                                        :value="option.value"
                                        v-for="option in searchform.status.options"
                                        :key="option"
                                        />
                                    </el-select>
                                    </el-form-item>
                                </el-col>
                                </el-row>
                            </merakColapse>
                            </el-form>
                            <!-- 表单 -->
                        </div>
                        </el-scrollbar>
                    </div>
                    <div class="modal-footer">
                        <el-button type="default" @click="closeModal">{{$t("merak.cancel")}}</el-button>
                        <el-button type="primary" @click="searchSubmitForm(ruleFormRef)">{{$t("merak.cancel")}}</el-button>
                        <el-button type="success" @click="showPlanModal">保存搜索方案</el-button>
                    </div>
                    </div>
                    <!--  高级搜索弹出框内容-->
                </template>
                <!-- /高级搜索弹出框 插槽-->


                   
            </searchBar>
            </div>
      <div class="merak-table-wrapper">
        <MerakXTable ref="tableRef" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
                    :query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params" 
                    :column-min-width="120"
                    :column-type="[{type: 'handle', width: 200, slot: 'handler' }]"
                    :batches="[{text: '批量更改测试信息', color: 'green', },{ text: '批量删除', color: 'red' }]"
                    :batch-click="handleBatchClick">

                    <template #handler="{ row }">
                        <div>
                            <el-button type="primary" link  @click="saveEdit(row)"> {{$t("manage_list.edit")}} </el-button>
                            <el-button type="primary" link  @click="showRemaining(row)"> {{$t("manage_list.log")}} </el-button>
                        </div>
                    </template>


                </MerakXTable>
      </div>
    </div>




    
    
  <!-- 新增抽屉start -->

  <el-dialog modal-class="merak_modal" v-model="drawerTranslation" direction="rtl"
                :close-on-click-modal="false" :close-on-press-escape="false"  width="700">
                <template #header>
                    <div class="merak_modal_title">{{$t("manage_list.edit")}}</div>
                </template>
                <div  >
                    <el-form :model="leavesForm" ref="leavesRef" :rules="leavesRules"
                        label-position="top">
                        <el-row :gutter="40">
                            <el-col :span="12">
                                <el-form-item :label='$t("manage_list.set_type")' prop="action">
                                    <el-select v-model="leavesForm.action" class="qf_select" style="width:100%">
                                        <el-option value="1" :label='$t("manage_list.jiaadd")'>{{$t("manage_list.jiaadd")}}</el-option>
                                        <el-option value="2" :label='$t("manage_list.jiadel")'>{{$t("manage_list.jiadel")}}</el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item :label='$t("manage_list.daynum")' prop="days">
                                    <el-input v-number:1=2  class="qf_input" v-model="leavesForm.days" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="40">
                          
                            <el-col :span="12">
                                <el-form-item :label='$t("manage_list.jiatype")' prop="category">
                                   
                                   <el-select v-model="year" disabled class="qf_select" style="width:100%">
                                        <el-option value="0"  :label='$t("manage_list.yearjia")'>{{$t("manage_list.yearjia")}}</el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item :label='$t("manage_list.reason_info_jia")'>
                                
                                    <el-input class="qf_input" 
                                    v-model="leavesForm.reason_info"
                                    
                                    
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>



                    </el-form>

                </div>


                <template #footer>
                    <el-button type="default" @click="cancelEmpty(leavesRef)">{{$t("merak.cancel")}}</el-button>
                    <el-button type="primary" @click="submitForm('1',leavesRef)">{{$t("merak.save")}}</el-button>

                </template>
            </el-dialog>

            <!-- 新增抽屉end -->




              <!-- 年假日志start -->

            <el-dialog modal-class="merak_modal" v-model="showRemainingModal" direction="rtl"
                :close-on-click-modal="false" :close-on-press-escape="false"  width="800">
                <template #header>
                    <div class="merak_modal_title"> {{$t("manage_list.nianjiajilu")}}</div>
                </template>
                <div class="" style="max-height: 500px;overflow-y: auto;">

                    <el-table class="merak-table-container" :data="showRemainingData" border style="width: 100%">
                        <el-table-column prop="update_at" :label='$t("manage_list.update_at")'  />
                        <el-table-column prop="days" :label='$t("manage_list.days")'  />
                        <el-table-column prop="action" :label='$t("manage_list.action")' />
                        <el-table-column prop="employee_name" :label='$t("manage_list.employee_name")' />
                    </el-table>
                  

                </div>

               
            </el-dialog>

            <!-- 年假日志end -->

    </div>






</template>

<script lang="ts" setup name="manageLeave">
    import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';

    import { ref, reactive, onMounted, getCurrentInstance } from "vue";

    
    import searchBar from "@/components/SearchBar";
    import merakColapse from "@/components/merakColapse/index.vue";
    import selectedParams from "@/components/SearchBar/components/selectedParams.vue";


    import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
    import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
    import { getleavesHeadApi, getleavesListApi ,getleavesremainingApi ,getjlApi} from "@/api/modules/personalManagementApi/holiday";
    import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
    import { getLocationParams } from "@/utils/index";

    import type { ElForm } from "element-plus";
    type FormInstance = InstanceType<typeof ElForm>;
    const leavesRef = ref < FormInstance > ();

    const { proxy } = getCurrentInstance();


    const tableRef = ref < MerakXTableInstance > ();

    const org_id=ref("")



 
    const year=ref('0')
    const showRemainingModal=ref(false)
    const showRemainingData =ref([]);

    //打开年假日志
    const showRemaining=(row)=>{
        showRemainingModal.value=true;
        getRemaining(row.user_id)
    }
	const getRemaining = (user_id) => {

		getjlApi({ user_id: user_id }).then(res => {
                if (res.code == ResultEnum.SUCCESS) {
                    const list = res.data.table_data.list;
                    showRemainingData.value = list;

                }
            })
	}

    //接收url参数
    const newUrl = new URL(window.location.href);
    let url_org_id = getLocationParams(newUrl.href,'org_id');
    org_id.value=url_org_id;

    //批量操作
    const handleBatchClick= async (e)=>{
       
  
    }


    //#region 搜索表单
    const search_val = ref("");
    const searchFn=(e)=>{
        console.log(e)
        // e.searchVal
        state.params.key_words=e.search;
    }


    const nodeChange=(data:any)=>{
        console.log(data)
		// 构建新的URL
		const newUrl = new URL(window.location.href);
		//console.log(newUrl)
		newUrl.searchParams.set('org_id', data.org_id);
        org_id.value= data.org_id;
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());

        search_val.value="";

        console.log(search_val.value)
		tableRef.value?.reloadData();
    }

    //#endregion

    //#region  同步翻译 publishJs
    const simultaneousTrans=()=>{
        publishJs().then(res=>{
            if (res.code == ResultEnum.SUCCESS) {
                successMsg('同步成功!请重新加载。');
            }
        })
    }

    //#endregion

    //#region 新增、编辑、删除
    const drawerTranslation = ref(false);
    const leavesTitle = ref("年假编辑");
    //表单参数结构
    const leavesForm = ref < leavesForm > ({
        user_id: "",
        action: "",
        days: "",
        reason_info: "",
    })
    
    const validateDay = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error(proxy.$t("main.requiredMsg")))
        } else {
            let reg = /^-?(0|([1-9][0-9]*))(\.[\d]+)?$/;

            if (reg.test(value)) {
                
                console.log(value%0.5)
               
                    if(value%0.5 == 0){
                        if(value>100){
                            callback(new Error("必须小于100"))
                        }

                        }else{
                            callback(new Error("至少是0.5的倍数"))
                        }
                
               

            } else {



                callback(new Error("至少是0.5的倍数"))

                
            }
            callback()
        }
    };
    const leavesRules = reactive({
        action: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
        days: [{ required: true,validator: validateDay, trigger: "blur" }],
    
    });
    //新增操作
    const onPlus = () => {
        leavesForm.value = {
            user_id: "",
            action: "",
            days: "",
            reason_info: "",
        }
        //打开弹窗
        drawerTranslation.value = true;
    };
    //保存并继续
    const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
        submitForm(typebtn, formEl)
    }

    const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
        if (!formEl) return;
        await formEl.validate((valid, fields) => {
            if (valid) {
                //保存
                postAdd(typebtn, formEl);
                console.log("submit!");
            } else {
                console.log("error submit!", fields);
            }
        });
    };
    const resetForm = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.resetFields()
	}
    //新增  
    /**
     * typebtn 1保存 2保存并继续
    */
    const postAdd = (typebtn: string, formEl: FormInstance | undefined) => {
        getleavesremainingApi(leavesForm.value).then(res => {
            console.log(res)
            if (res.code == ResultEnum.SUCCESS) {
                successMsg('保存成功!');
                if (typebtn == 1) {
                    //关闭弹窗
                    drawerTranslation.value = false;
                }
                formEl.resetFields();
                tableRef.value?.reloadData();
            }
            if (res.code == ResultEnum.ERROR) {
                failMsg(res.message);
            }
        }, err => {
            console.log(err)
        })
    }
    //编辑

    const saveEdit = (row: leavesForm) => {

        leavesForm.value = {
            user_id: row.user_id,
            action: "",
            days: "",
            reason_info: "",
        }
        //打开弹窗
        resetForm(leavesRef.value)
        
        drawerTranslation.value = true;
    }

    //取消
    const cancelEmpty = (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        formEl.resetFields();
        drawerTranslation.value = false;
    }


    //#endregion


    //权限数据
    // let authArr=ref({});
    let authArr=reactive({});

    //列表内容展示区
    const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => { 
        const params: Record<string, any> = {}; 
        if (!!page) {
            console.log(params)
            if(org_id.value==false){
    
                org_id.value=''
            }
            console.log(org_id.value)
            console.log(from)
           


            Object.assign(params, { ...page ,org_id:org_id.value});
     
            
        }
        console.log(from)
        for(let key of Object.keys(from)) {
            if (!!from[key]) {
                params[key]=from[key]
            }
        }
        return await getleavesListApi(params).then(res => {
            console.log(res)
            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data;
            
                Object.assign(authArr,data.auth_list)

                const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };
            
                return table_data;
            }
        })

    };


 
    //表头信息
    const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
        return await getleavesHeadApi().then(res => {
            if (res.code == ResultEnum.SUCCESS) {


              

                let data = res.data as MerakXTableQuery.Columns;
                // const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };

                  //获取表头后使用tableid 获取搜索方案
                  queryFilterOptions(data);

                state.columns = data.columns;
                return data;
            }
        })
    };













// 获取高级搜索方案
const queryFilterOptions = async data => {
  searchbar.value.getPlanList(data.table_id);
  // 初始化接口需要传入队列 loading 暴露的 id
};

    // 高级搜索表单
const ruleFormRef = ref<FormInstance>();
const searchform = ref({
  org_company: {
    label: "公司",
    value: "",
    type: "select",
    options: [
      { label: "北京企发", value: 1 },
      { label: "米格速达", value: 2 },
      { label: "新世纪农业", value: 3 }
    ]
  },
  org_department: {
    label: "部门",
    value: "",
    type: "select",
    options: [
      { label: "物流", value: 1 },
      { label: "研发", value: 2 },
      { label: "销售", value: 3 }
    ]
  },
  job_nature: {
    label: "工作性质",
    value: "",
    type: "select",
    options: [
      { label: "全职", value: 1 },
      { label: "兼职", value: 2 }
    ]
  },
  status: {
    label: "状态",
    value: "",
    type: "select",
    options: [
      { label: "在职", value: 1 },
      { label: "试用期", value: 2 }
    ]
  }
});

//高级搜索模态
const searchbar = ref();




const state = reactive < {
        params: Record < string, any>;
        columns: MerakXTableColumn[];
    } > ({
        params: {
            key_words: ""
        },
        columns: []
    }); 




//点击取消按钮关闭高级搜索模态框
const closeModal = () => {
  searchbar.value.modalHide();
  searchbar.value.clear();
};

//打开搜索方案弹出
const showPlanModal = () => {
  searchbar.value.showPlanModal();
};

//搜索表单提交
const searchSubmitForm = async (formEl: FormInstance | undefined) => {
  state.params =  { ...searchbar.value.formParams("value") };
  searchbar.value.clear();
  searchbar.value.clear();
  searchbar.value.modalHide();
};


//触发了快速搜索或者搜索方案
const searchBarPost = params => {
console.log(params)
  let postParams = { ...params.params,  search: params.search  };
  state.params = postParams;
};



</script>

<style scoped lang="scss">
    .translation {
        /* display: flex;
        flex-direction: column;
        width: 100%;*/
        height: 100%;


    }
    .translation_card {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;

        .table_main {
            /* display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%; */
            flex: auto;
            min-height: 0;
        }
    }

    .translationPad {
        padding: 15px;
    }
</style>